#!/usr/bin/env python
# -*- coding: UTF-8 -*-

'''
ConstNode 为了实现一个输出恒为1的节点(计算偏置项时需要)
'''
class ConstNode(object):
    def __init__(self, layer_index, node_index):
        '''
        构造节点对象
        :param layer_index: 节点输出层的编号
        :param node_index:  节点的编号
        '''
        self.layer_index = layer_index
        self.node_index = node_index
        self.up_stream = []
        self.down_stream = []
        self.output = 0
        self.delta = 0

    def append_down_stream_connection(self, conn):
        self.down_stream.append(conn)


    def calc_hidden_layer_delta(self):
        '''
        节点属于隐含层，根据δ = a * (1- a) * ∑(δk * ωkj)  k 下层节点索引， ωki 为 隐含节点j到下层节点j的权值
        '''
        down_stream_delta = reduce(lambda ret, conn: ret + conn.down_stream_node.delta * conn.weight, self.down_stream, 0.0)
        self.delta = self.output * (1 - self.output) * down_stream_delta


    def __str__(self):
        '''
       打印节点的信息
       '''
        node_str = '%u-%u: output: 1' % (self.layer_index, self.node_index)
        downs_tream_str = reduce(lambda ret, conn: ret + '\n\t' + str(conn), self.down_stream, '')
        return node_str + '\n\tdown_stream:' + downs_tream_str